import { InjectionKey } from 'vue'
import { createStore, Store, useStore as baseUseStore } from 'vuex'
import { RootStateTypes } from './interface'

// 自动化引入 module
const files = require.context('./modules', false, /\.ts$/)
const storeModuleNames: string[] = []

const modules = files.keys().reduce((modules, path) => {
    const name = path.replace(/(.*\/)*([^.]+).*/gi, '$2')

    // store module 唯一性校验
    if (!storeModuleNames.some((k) => k === name)) {
        storeModuleNames.push(name)
    } else {
        throw new Error(`Store 配置中存在重复的 Module，文件：${path}`)
    }

    modules[name] = files(path).default
    return modules
}, {})

/**
 * 定义类型化
 */
export const key: InjectionKey<Store<RootStateTypes>> = Symbol('router')

export function useStore() {
    return baseUseStore(key)
}

/**
 * 导出 Store 实例
 */
export default createStore<RootStateTypes>({
    modules
})
